package leetcode.hard;

import leetcode.base.ListNode;

import java.util.PriorityQueue;

/**
 * ClassName: $23_MergeKLists
 * Description:
 * date: 2021-12-09 13:10
 *
 * @author liyifan
 */
public class $23_MergeKLists {
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0)
            return null;
        ListNode head = new ListNode(-1);
        ListNode p = head;
        PriorityQueue<ListNode> queue = new PriorityQueue<>(lists.length, (a, b)-> a.val - b.val);
        for (ListNode node:lists) {
            if (node != null)
                queue.add(node);
        }
        while (!queue.isEmpty()) {
            ListNode poll = queue.poll();
            p.next = poll;
            p = p.next;
            if (poll.next != null) {
                queue.add(poll.next);
            }
        }
        return head.next;
    }
}
